{% extends "members/base.html" %}

{% block title %}我的量表{% endblock %}

{% block extra_css %}
<style>
    .scale-card {
        transition: transform 0.2s, box-shadow 0.2s;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        overflow: hidden;
    }
    .scale-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    .status-badge {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
        border-radius: 12px;
        font-weight: 500;
    }
    .status-draft {
        background-color: #ffeaa7;
        color: #2d3436;
    }
    .status-published {
        background-color: #00b894;
        color: white;
    }
    .status-archived {
        background-color: #636e72;
        color: white;
    }
    .stats-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        padding: 1.5rem;
        margin-bottom: 1rem;
    }
    .filter-tabs .nav-link {
        border: none;
        color: #6c757d;
        background: transparent;
        border-radius: 20px;
        padding: 0.5rem 1rem;
        margin-right: 0.5rem;
    }
    .filter-tabs .nav-link.active {
        background-color: #007bff;
        color: white;
    }
    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
        color: #6c757d;
    }
    .empty-state i {
        font-size: 4rem;
        opacity: 0.5;
        margin-bottom: 1rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1">我的量表</h2>
            <p class="text-muted mb-0">管理您创建的量表</p>
        </div>
        <a href="{{ url_for('members.scale_creator') }}" class="btn btn-primary">
            <i class="bi bi-plus-circle me-2"></i>创建新量表
        </a>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4" id="stats-container">
        <div class="col-md-12">
            <div class="stats-card">
                <div class="row align-items-center">
                    <div class="col-md-3 text-center">
                        <div class="h2 mb-0" id="total-scales">-</div>
                        <div class="small">总量表数</div>
                    </div>
                    <div class="col-md-3 text-center">
                        <div class="h2 mb-0" id="published-scales">-</div>
                        <div class="small">已发布</div>
                    </div>
                    <div class="col-md-3 text-center">
                        <div class="h2 mb-0" id="draft-scales">-</div>
                        <div class="small">草稿</div>
                    </div>
                    <div class="col-md-3 text-center">
                        <div class="h2 mb-0" id="remaining-quota">-</div>
                        <div class="small">剩余配额</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 过滤标签 -->
    <div class="mb-4">
        <ul class="nav filter-tabs">
            <li class="nav-item">
                <a class="nav-link active" href="#" data-status="" onclick="filterScales('')">全部</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-status="DRAFT" onclick="filterScales('DRAFT')">草稿</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-status="PUBLISHED" onclick="filterScales('PUBLISHED')">已发布</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-status="ARCHIVED" onclick="filterScales('ARCHIVED')">已归档</a>
            </li>
        </ul>
    </div>

    <!-- 量表列表 -->
    <div id="scales-container">
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在加载量表...</p>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container" class="mt-4"></div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除量表 "<span id="delete-scale-title"></span>" 吗？</p>
                <p class="text-warning"><i class="bi bi-exclamation-triangle me-2"></i>此操作不可撤销！</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">删除</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentPage = 1;
let currentStatus = '';
let scaleToDelete = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadStats();
    loadScales();
});

// 加载统计信息
function loadStats() {
    apiRequest('/api/scales/my/stats')
        .then(response => {
            if (response.success) {
                const stats = response.data;
                document.getElementById('total-scales').textContent = stats.created_count || 0;
                document.getElementById('published-scales').textContent = stats.published_count || 0;
                document.getElementById('draft-scales').textContent = stats.draft_count || 0;
                
                if (stats.scale_limit === -1) {
                    document.getElementById('remaining-quota').textContent = '无限';
                } else {
                    document.getElementById('remaining-quota').textContent = stats.remaining_quota || 0;
                }
            }
        })
        .catch(error => {
            console.error('加载统计信息失败:', error);
        });
}

// 加载量表列表
function loadScales(page = 1, status = '') {
    currentPage = page;
    currentStatus = status;
    
    let url = `/api/scales/my?page=${page}&per_page=12`;
    if (status) {
        url += `&status=${status}`;
    }
    
    apiRequest(url)
        .then(response => {
            if (response.success) {
                renderScales(response.data.scales);
                renderPagination(response.data.pagination);
            } else {
                showError('加载量表失败: ' + response.message);
            }
        })
        .catch(error => {
            console.error('加载量表失败:', error);
            showError('加载量表失败，请稍后重试');
        });
}

// 渲染量表列表
function renderScales(scales) {
    const container = document.getElementById('scales-container');
    
    if (!scales || scales.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-journal-text"></i>
                <h4>暂无量表</h4>
                <p>您还没有创建任何量表，<a href="${window.location.origin}/members/scale-creator">点击这里</a>创建您的第一个量表吧！</p>
            </div>
        `;
        return;
    }
    
    let html = '<div class="row">';
    
    scales.forEach(scale => {
        const statusClass = `status-${scale.status.toLowerCase()}`;
        const statusText = getStatusText(scale.status);
        
        html += `
            <div class="col-lg-4 col-md-6 mb-4">
                <div class="card scale-card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h5 class="card-title mb-0">${escapeHtml(scale.title)}</h5>
                            <span class="status-badge ${statusClass}">${statusText}</span>
                        </div>
                        
                        ${scale.subtitle ? `<p class="card-subtitle text-muted mb-2">${escapeHtml(scale.subtitle)}</p>` : ''}
                        
                        <p class="card-text text-muted small mb-3">${escapeHtml(scale.description)}</p>
                        
                        <div class="row text-center mb-3">
                            <div class="col-4">
                                <div class="small text-muted">题目数</div>
                                <div class="fw-bold">${scale.question_count || 0}</div>
                            </div>
                            <div class="col-4">
                                <div class="small text-muted">使用次数</div>
                                <div class="fw-bold">${scale.usage_count || 0}</div>
                            </div>
                            <div class="col-4">
                                <div class="small text-muted">创建时间</div>
                                <div class="fw-bold">${formatDate(scale.created_at)}</div>
                            </div>
                        </div>
                        
                        <div class="d-flex flex-column gap-2">
                            <!-- 第一行按钮 -->
                            <div class="btn-group w-100" role="group">
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="viewScaleDetail(${scale.id})">
                                    <i class="bi bi-info-circle me-1"></i>详情
                                </button>
                                <button type="button" class="btn btn-outline-info btn-sm" onclick="previewScale(${scale.id})">
                                    <i class="bi bi-eye me-1"></i>预览
                                </button>
                                <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteScale(${scale.id}, '${escapeHtml(scale.title)}')">
                                    <i class="bi bi-trash me-1"></i>删除
                                </button>
                            </div>
                            
                            <!-- 第二行编辑按钮 -->
                            <div class="btn-group w-100" role="group">
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="editBasicInfo(${scale.id})">
                                    <i class="bi bi-pencil me-1"></i>修改基本信息
                                </button>
                                ${scale.status === 'DRAFT' ? `
                                    <button type="button" class="btn btn-outline-warning btn-sm" onclick="editQuestions(${scale.id})">
                                        <i class="bi bi-list-ul me-1"></i>修改题目设计
                                    </button>
                                ` : ''}
                            </div>
                            
                            <!-- 第三行发布按钮（仅草稿状态） -->
                            ${scale.status === 'DRAFT' ? `
                                <button type="button" class="btn btn-success btn-sm w-100" onclick="publishScale(${scale.id})">
                                    <i class="bi bi-upload me-1"></i>发布量表
                                </button>
                            ` : ''}
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    container.innerHTML = html;
}

// 渲染分页
function renderPagination(pagination) {
    const container = document.getElementById('pagination-container');
    
    if (pagination.pages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let html = '<nav><ul class="pagination justify-content-center">';
    
    // 上一页
    if (pagination.has_prev) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadScales(${pagination.page - 1}, '${currentStatus}')">上一页</a></li>`;
    }
    
    // 页码
    for (let i = 1; i <= pagination.pages; i++) {
        const activeClass = i === pagination.page ? 'active' : '';
        html += `<li class="page-item ${activeClass}"><a class="page-link" href="#" onclick="loadScales(${i}, '${currentStatus}')">${i}</a></li>`;
    }
    
    // 下一页
    if (pagination.has_next) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadScales(${pagination.page + 1}, '${currentStatus}')">下一页</a></li>`;
    }
    
    html += '</ul></nav>';
    container.innerHTML = html;
}

// 过滤量表
function filterScales(status) {
    // 更新标签状态
    document.querySelectorAll('.filter-tabs .nav-link').forEach(link => {
        link.classList.remove('active');
    });
    event.target.classList.add('active');
    
    // 重新加载
    loadScales(1, status);
}

// 查看量表详情
function viewScaleDetail(scaleId) {
    window.location.href = `/members/scales/${scaleId}`;
}

// 编辑量表基本信息
function editBasicInfo(scaleId) {
    window.location.href = `/members/scale-creator?id=${scaleId}&mode=basic`;
}

// 编辑量表题目设计
function editQuestions(scaleId) {
    window.location.href = `/members/scale-creator?id=${scaleId}&mode=questions`;
}

// 编辑量表（保留原函数以兼容其他地方的调用）
function editScale(scaleId) {
    window.location.href = `/members/scale-creator?id=${scaleId}`;
}

// 预览量表
function previewScale(scaleId) {
    window.open(`/scales/${scaleId}/preview`, '_blank');
}

// 发布量表
function publishScale(scaleId) {
    if (confirm('确定要发布这个量表吗？发布后将对所有用户可见。')) {
        apiRequest(`/api/scales/${scaleId}/publish`, {
            method: 'POST'
        })
        .then(response => {
            if (response.success) {
                alert('量表发布成功！');
                loadScales(currentPage, currentStatus);
                loadStats();
            } else {
                alert('发布失败: ' + response.message);
            }
        })
        .catch(error => {
            console.error('发布量表失败:', error);
            alert('发布失败，请稍后重试');
        });
    }
}

// 删除量表
function deleteScale(scaleId, scaleTitle) {
    scaleToDelete = scaleId;
    document.getElementById('delete-scale-title').textContent = scaleTitle;
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
}

// 确认删除
function confirmDelete() {
    if (!scaleToDelete) return;
    
    apiRequest(`/api/scales/${scaleToDelete}/delete`, {
        method: 'DELETE'
    })
    .then(response => {
        if (response.success) {
            bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
            alert('量表删除成功！');
            loadScales(currentPage, currentStatus);
            loadStats();
        } else {
            alert('删除失败: ' + response.message);
        }
    })
    .catch(error => {
        console.error('删除量表失败:', error);
        alert('删除失败，请稍后重试');
    })
    .finally(() => {
        scaleToDelete = null;
    });
}

// 工具函数
function getStatusText(status) {
    const statusMap = {
        'DRAFT': '草稿',
        'PUBLISHED': '已发布',
        'ARCHIVED': '已归档'
    };
    return statusMap[status] || status;
}

function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN');
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function showError(message) {
    const container = document.getElementById('scales-container');
    container.innerHTML = `
        <div class="alert alert-danger" role="alert">
            <i class="bi bi-exclamation-triangle me-2"></i>${message}
        </div>
    `;
}
</script>
{% endblock %}